package common.controller;

import implementor.IssueSlipImplementor;
import implementor.IssueSlipItemImplementor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import model.IssueSlipItem;
import model.Material;

import common.view.IssueSlipView;

import dao.IssueSlipDao;
import dao.IssueSlipItemDao;
import dbhandelling.Connections;
import dto.IssueSlip;
import dto.MaterialSpecification;
import utility.AppUtilities;
import utility.Constants;
import utility.ViewUtilities;


public class IssueSlipController implements ActionListener{
	private IssueSlipView view;
	private IssueSlip model;
	private MaterialAdderController contrl;
	private static int srNo=1;
	private Vector<IssueSlipItem>slipItems;
	private static int srno=1;
	
	/*
	 * Please check weather , IssueSlip dto has model attributes.Remember that this case is view to 
	 * Db so you will not need model attributes. We need them when we go from dto to view.
	 */
	
	private IssueSlip issueSlip;
	
	
	// Constructor.
	
	 public IssueSlipController(IssueSlipView view, IssueSlip model) throws Exception {
			super();
			this.view = view;
			this.model = model;
			AppUtilities.fillProjectNameCombo(view.getCbProject());
			AppUtilities.fillContractorCombo(view.getCbContractor());
			AppUtilities.fillBuildingCombo(view.getCbBldgNo());
			AppUtilities.fillFlatCombo(view.getCbFlatNo());
			AppUtilities.fillEmployeeCombo(view.getCbSiteEngineer());
			view.actionlisteners(this);
			slipItems=new Vector<IssueSlipItem>();
			contrl=new MaterialAdderController(view.getmAdder(), null);
			view.getmAdder().getBtnAdd().addActionListener(this);
		}


	
	 
	private void addInTable()
	 {
		  Material material = contrl.getModel();
		   IssueSlipItem i = new IssueSlipItem();
		   i.setModelmaterial(material);
		   i.setmCode(material.getMCode());
		   i.setSpecCode(material.getCurrentSpecs().getAutoSpecCode());
		  
		  
		   
		   DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
		   Material tempm=i.getModelmaterial();
		   MaterialSpecification specs= i.getModelmaterial().getCurrentSpecs();
		   
		   dm.addRow(new Object[]{srNo++,tempm.getMCode(),tempm.getMname(),specs.getmSpecs(),tempm.getUnit()});
		   
		   slipItems.add(i);
		 
	 }
	
	
	
	private void reactToSave() throws Exception
	 {
		Connection con =Connections.getMyConnection();
		try {
			con.setAutoCommit(false);
			int slipId= this.saveToIssueSlip();
			this.saveToIssueItems(slipId);
		} catch (Exception e) {
			con.rollback();
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		con.commit();
		con.setAutoCommit(true);
	 }
	
	
	private int saveToIssueSlip() throws Exception
	{
		IssueSlipDao isDao=new IssueSlipImplementor();
		model=new IssueSlip();
		model.setIssueNo(12);
		model.setIdContractor(AppUtilities.getContractorId(view.getCbContractor().getSelectedItem().toString()));
		model.setIdEmployee(AppUtilities.getGeneratedById(view.getCbSiteEngineer().getSelectedItem().toString()));
		model.setIdProject(AppUtilities.getProjectId(view.getCbProject().getSelectedItem().toString()));
		model.setBldgNo(AppUtilities.getBuildingId(view.getCbBldgNo().getSelectedItem().toString()));
		model.setFlatNo(AppUtilities.getFlatId(view.getCbFlatNo().getSelectedItem().toString()));
		model.setGenratedDate(ViewUtilities.convert(view.getTfDate().getText().trim()));
		model=new IssueSlip(0, model.getIssueNo(), model.getIdContractor(), model.getIdEmployee(), model.getIdProject(), model.getBldgNo(), model.getFlatNo(), model.getGenratedDate(), Constants.ACTIVE);
		isDao.add(model);
		int autoissueSlipNo= isDao.getAutoId();
		return autoissueSlipNo;
		
	}
	
	
	private void saveToIssueItems(int autoIssueSlipItemid) throws  Exception
	{
	   
		int i =0;
		for(;i<this.slipItems.size();i++)
			this.slipItems.get(i).setSlipNo(autoIssueSlipItemid);
		
		IssueSlipItemDao slipItemsDao = new IssueSlipItemImplementor();
		for(i=0;i<slipItems.size();i++)
			slipItemsDao.add(this.slipItems.get(i));
	   
	}
	
	public void fillViewFromModel() throws Exception
	{		
	  view.getLblIssueNo1().setText(model.getIssueNo()+"");
	  view.getTextFieldDate().setText(model.getGenratedDate()+"");
	  String[]projectName={model.getModelprojectName()};
	  ViewUtilities.set_comboBox(view.getCbProject(),projectName);
	  String[]contractorName = {model.getmodelcontractorName()};
	  String[]employee = {model.getModelEmployeeName()};
	  String[]buildingNo= {model.getModelBldgName()};
	  String []flatNo={model.getModelFlatName()};
	  ViewUtilities.set_comboBox(view.getCbContractor(),contractorName);
	  ViewUtilities.set_comboBox(view.getCbSiteEngineer(), employee);
	  ViewUtilities.set_comboBox(view.getCbBldgNo(), buildingNo);
	  ViewUtilities.set_comboBox(view.getCbFlatNo(), flatNo);
	  
	  JTable table = view.getTable();
	  DefaultTableModel dm = (DefaultTableModel) table.getModel();
	  for(int i=0;i<model.getModelslipitems().length;i++)
	  {
		  IssueSlipItem temp = model.getModelslipitems()[i];
		  Material temp1= temp.getModelmaterial();
		  dm.addRow(new Object[]{srno++,temp1.getMCode(),temp1.getMname(),temp1.getCurrentSpecs().getmSpecs()
				  ,temp1.getUnit(),temp.getRequiredQuant(),temp.getIssueQuant()});
	  }
	  
	  
	  
	  
	  
	}
	
	private void delete(int row)
	{
		JTable table=view.getTable();
		DefaultTableModel dm = (DefaultTableModel) table.getModel();
		dm.removeRow(row);
		slipItems.remove(row);
	}


	
	
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getSource()==view.getBtnDate())
		{
			ViewUtilities.makeDateComponent(view.getTfDate());
			
		}
		
		if(arg0.getSource() == view.getmAdder().getBtnAdd())
		{
			contrl.changeModel();
			addInTable();
		}
		
		if(arg0.getSource() == view.getBtnSave())
			try {
				reactToSave();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		
	}
	
	
	
	 
	 
	 
	 
	 
	 
	



}
